import React from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/custom/button";
import { PasswordInput } from "@/components/custom/password-input";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { userLogin } from "@/api/system";
import { setUserAction } from "@/store/actions";
import { useDispatch } from "react-redux";
import { Link, useNavigate } from "react-router-dom";
import { store } from "@/store/configureStore";
import { useToast } from "@/hooks/use-toast";
import bysyLogo from "@/assets/images/bysy_logo.png";
import { encryptStr } from "@/lib/utils";

const Login: React.FC = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [submitting, setSubmitting] = React.useState<boolean>(false);
  const [loginMessage, setLoginMessage] = React.useState<string>("");
  const { toast } = useToast();

  const formSchema = z.object({
    username: z.string({ required_error: "请输入用户名" }).min(3, {
      message: "用户名长度至少3位",
    }),
    password: z.string().min(8, {
      message: "密码长度至少8位",
    }),
  });

  type FormValuesT = z.infer<typeof formSchema>;

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: "",
      password: "",
    },
    mode: "onChange",
  });

  // 自定义错误处理器
  function handleBackendErrors(
    errorsFromBackend: Record<string, string>,
    validationErrors: z.ZodIssue[]
  ) {
    const customErrors: Partial<Record<keyof FormData, string>> = {};

    Object.keys(errorsFromBackend).forEach((key) => {
      if (validationErrors.some((error) => error.path.includes(key))) {
        customErrors[key as keyof FormData] = errorsFromBackend[key];
      }
    });

    return customErrors;
  }

  const onSubmit = (values: any) => {
    userLogin({
      username: encryptStr(values.username),
      password: encryptStr(values.password),
    })
      .then((res) => {
        setSubmitting(false);
        console.log(res);
        if (res.data.accessToken) {
          store.dispatch(setUserAction(res.data));
          navigate("/");
        } else {
          navigate("/login");
        }
      })
      .catch((err: any) => {
        setSubmitting(false);
        console.log(err);
        setLoginMessage(err.detail);
        // toast({
        //   variant: "destructive",
        //   title: "登录失败",
        //   description: "请检查网络或联系系统管理员",
        // });
      });
  };

  return (
    <>
      <div
        className="container relative grid h-screen flex-col items-center justify-center lg:max-w-none lg:grid-cols-2 lg:px-0"
        style={{ height: "100vh" }}
      >
        <div className="relative hidden h-full flex-col bg-muted p-10 text-white dark:border-r lg:flex">
          <div className="absolute inset-0 bg-blue-600" />
          <div className="relative z-20 flex items-center text-lg font-medium justify-between">
            <img src={bysyLogo} className="h-12" />
            <span className="text-2xl font-bold">药学信息服务区</span>
          </div>

          {/* <img
            src={logo}
            className="relative m-auto"
            width={301}
            height={60}
            alt="Vite"
          /> */}

          <div className="relative z-20 mt-auto">
            <blockquote className="space-y-2">
              <p className="text-lg">
                &ldquo;请您保管好个人账号密码，防止数据泄漏事件发生&rdquo;
              </p>
              <footer className="text-sm text-right">
                北京大学第三医院 信息管理与大数据中心
              </footer>
            </blockquote>
          </div>
        </div>
        <div className="lg:p-8">
          <div className="mx-auto flex w-full flex-col justify-center space-y-2 sm:w-[350px]">
            <div className="flex flex-col space-y-2 text-center">
              <h1 className="text-2xl font-semibold tracking-tight">登录</h1>
            </div>
            {/* <Button onClick={handleClick}>SM4</Button> */}
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onSubmit)}
                className="space-y-8"
              >
                <div className="grid gap-2">
                  <FormField
                    control={form.control}
                    name="username"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>用户名</FormLabel>
                        <FormControl>
                          <Input placeholder="用户名" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="password"
                    render={({ field }) => (
                      <FormItem>
                        <div className="flex items-center justify-between">
                          <FormLabel>密码</FormLabel>
                          <Link
                            to="/forgot-password"
                            className="text-sm font-medium text-muted-foreground hover:opacity-75"
                          >
                            忘记了密码？
                          </Link>
                        </div>
                        <FormControl>
                          <PasswordInput placeholder="密码" {...field} />
                        </FormControl>
                        <FormDescription className="text-red-600">
                          {loginMessage}
                        </FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <Button className="mt-2" loading={submitting}>
                    提交
                  </Button>
                </div>
              </form>
            </Form>
          </div>
        </div>
      </div>
    </>
  );
};

export default Login;
